package org.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.x.protobuf.MysqlxSession;
import org.example.dao.TableInfoDao;
import org.example.pojo.TableArea;
import org.example.pojo.TableInfo;
import org.example.service.TableAreaService;
import org.example.service.TableInfoService;
import org.example.uitl.Query;
import org.example.uitl.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/tableArea")
public class TableAreaController {
    @Autowired
    private TableAreaService tableAreaService;
    @Autowired
    private TableInfoService tableInfoService;
    @Autowired
    private TableInfoDao tableInfoMapper;

    @RequestMapping("/FindTableArea")
    public Result FindTableArea(Query query){
        Page<TableInfo> page = tableInfoService.FindTableArea(query);
        return Result.OK(page);
    }


    @RequestMapping("/getarea")
    public Result getarea(){
        List<TableArea> list = tableAreaService.list();
        return Result.OK(list);
    }

    @RequestMapping("/tablelist")
    public Result tablelist(Query query){
        Page<TableInfo> list = tableInfoService.tablelist(query);
        return Result.OK(list);
    }

    @RequestMapping("/add")
    public Result add(TableInfo tableInfo){
        boolean save = tableInfoService.save(tableInfo);
        return save?Result.OK():Result.ERROR();
    }

    @RequestMapping("/update")
    public Result update(TableInfo tableInfo){
        boolean update = tableInfoService.updateById(tableInfo);
        return update?Result.OK():Result.ERROR();
    }

    @RequestMapping("/delete")
    public Result delete(Integer tableId){
        boolean delete = tableInfoService.removeById(tableId);
        return delete?Result.OK():Result.ERROR();
    }

    @RequestMapping("/addarea")
    public Result addarea(TableArea tableArea){
        boolean save = tableAreaService.save(tableArea);
        return save?Result.OK():Result.ERROR();
    }


    /**
     * 更新桌位状态（开台/结账）
     */
    @PutMapping("/updateTableStatus")
    public Map<String, Object> updateTableStatus(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        try {
            Integer tableId = (Integer) params.get("tableId");
            String status = (String) params.get("status");
            Date occupyTime = (Date) params.get("occupyTime");

            TableInfo table = tableInfoMapper.selectById(tableId);
            if (table == null) {
                result.put("code", 404);
                result.put("msg", "桌位不存在");
                return result;
            }

            table.setStatus(status);
            if (occupyTime != null) {
                table.setOccupyTime(occupyTime);
            }

            tableInfoMapper.updateById(table);

            result.put("code", 200);
            result.put("msg", "桌位状态更新成功");

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "更新失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 获取所有可用桌位（用于前端选择）
     */
    @GetMapping("/listAvailableTables")
    public Map<String, Object> listAvailableTables() {
        Map<String, Object> result = new HashMap<>();

        try {
            List<TableInfo> tables = tableInfoMapper.selectList(null);
            List<Map<String, Object>> availableTables = new ArrayList<>();

            for (TableInfo table : tables) {
                if ("idle".equals(table.getStatus())) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("tableId", table.getTableId());
                    map.put("tableNo", table.getTableNo());
                    map.put("capacity", table.getCapacity());
                    map.put("status", table.getStatus());
                    map.put("areaName", getAreaName(table.getAreaId()));
                    availableTables.add(map);
                }
            }

            result.put("code", 200);
            result.put("msg", "success");
            result.put("data", availableTables);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "查询失败：" + e.getMessage());
        }

        return result;
    }

    // 辅助方法：获取区域名称（可扩展为查字典表）
    private String getAreaName(Integer areaId) {
        switch (areaId) {
            case 1: return "A区";
            case 2: return "B区";
            case 3: return "C区";
            case 4: return "D区";
            case 5: return "E区";
            case 6: return "F区";
            default: return "未知";
        }
    }

}
